package com.davy.tx;

import android.Manifest;
import android.app.Dialog;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.provider.Settings;
import android.text.TextUtils;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import androidx.annotation.RequiresApi;
import androidx.appcompat.app.AlertDialog;
import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;
import androidx.core.content.FileProvider;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.bumptech.glide.Glide;
import com.bumptech.glide.load.resource.bitmap.RoundedCorners;
import com.bumptech.glide.request.RequestOptions;
import com.davy.tx.http.CommonHttpConsts;
import com.davy.tx.http.HttpCallbackData;
import com.davy.tx.http.HttpClient;
import com.davy.tx.tuicallkit.CallActivity;
import com.davy.tx.tuicallkit.GenerateTestUserSig;
import com.davy.tx.tuicallkit.GroupCallActivity;
import com.davy.tx.tuicallkit.setting.SettingsConfig;
import com.davy.tx.utils.DeviceIdHelper;
import com.davy.tx.utils.LogUtils;
import com.davy.tx.utils.SPUtils;
import com.davy.tx.utils.StringUtils;
import com.davy.tx.utils.ToastUtil;
import com.davy.tx.view.IndicatorProgressBar;
import com.google.gson.Gson;
import com.lzy.okgo.OkGo;
import com.lzy.okgo.callback.FileCallback;
import com.lzy.okgo.model.Progress;
import com.lzy.okgo.model.Response;
import com.tencent.qcloud.tuicore.TUILogin;
import com.tencent.qcloud.tuicore.interfaces.TUICallback;
import com.tencent.qcloud.tuicore.interfaces.TUILoginListener;
import com.tencent.qcloud.tuikit.tuicallkit.TUICallKit;

import java.io.File;
import java.util.HashMap;
import java.util.Map;

public class MainActivity extends BaseActivity {
    private long mExitTime = 0;//退出程序
    //    private TextView mTextUserId;
//    private TextView mTextNickname;
//    private ImageView mImageAvatar;
    private TextView tvName, tvJob;
    private ImageView imgUser;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        tvJob = findViewById(R.id.tvJob);
        tvName = findViewById(R.id.tvName);
        imgUser = findViewById(R.id.imgUser);

        destfiledir = Environment.getExternalStorageDirectory().getPath();
        LogUtils.e("tag", "destfiledir:" + destfiledir);
        mProgress = findViewById(R.id.update_progress);
        rl_softu = findViewById(R.id.rl_softu);
        lyDialog = findViewById(R.id.lyDialog);
        tvContext = findViewById(R.id.tvContext);
        tvDialogCancel = findViewById(R.id.tvDialogCancel);
        tvDialogConfirm = findViewById(R.id.tvDialogConfirm);
        rl_softu.setVisibility(View.GONE);
        rl_softu.setOnClickListener(v -> {
        });
        lyDialog.setOnClickListener(v -> {
        });

        tvDialogCancel.setOnClickListener(v -> lyDialog.setVisibility(View.GONE));
        tvDialogConfirm.setOnClickListener(v -> {
            lyDialog.setVisibility(View.GONE);
            rl_softu.setVisibility(View.VISIBLE);
            downloadNewFile();
        });

        String insertTime = SPUtils.get(mContext, "benS", "") + "";
        if (!StringUtils.isEmpty(insertTime)) {
            upLogInfo(insertTime);
        }

        new Handler().postDelayed(() -> upTrajectory(), 1200);

        upVersion();

        initView();

        initData();
        String userId = SPUtils.get(mContext, "userPhone", "") + "";// 请替换为您的UserId
        int sdkAppId = GenerateTestUserSig.SDKAPPID;// 请替换为第一步在控制台得到的SDKAppID
        String userSig = GenerateTestUserSig.genTestUserSig(userId);

        TUILogin.login(mContext, sdkAppId, userId, userSig, new TUICallback() {
            @Override
            public void onSuccess() {
                LogUtils.e("TAG", "登录成功");
                SettingsConfig.userId = userId;
                TUICallKit.createInstance(getApplication()).enableFloatWindow(SettingsConfig.isShowFloatingWindow);
                TUICallKit.createInstance(getApplication()).enableVirtualBackground(SettingsConfig.isShowBlurBackground);
                TUICallKit.createInstance(getApplication()).enableIncomingBanner(SettingsConfig.isIncomingBanner);
            }

            @Override
            public void onError(int errorCode, String errorMessage) {
                com.tencent.qcloud.tuicore.util.ToastUtil.toastShortMessage(getString(R.string.app_toast_login_fail, errorCode, errorMessage));
                LogUtils.e("TAG", errorCode + "登录失败;" + errorMessage);
            }
        });

        TUILogin.addLoginListener(mLoginListener);
        // 使用示例
        String sha1 = StringUtils.getSHA1("com.davy.tx");
        LogUtils.e("TAG", "SHA1: " + sha1);
        String md5 = StringUtils.getMD5("com.davy.tx");
        LogUtils.e("TAG", "md5: " + md5);
        LogUtils.e("tag", "DeviceIdHelper:" + DeviceIdHelper.getDeviceId(mContext));
    }

    private void initData() {
        // 设置图片的圆角半径为90dp
        int radius = 90;
        RequestOptions options = new RequestOptions().transform(new RoundedCorners(radius));
        Glide.with(mContext).load(SPUtils.get(mContext, "iconImg", "")).apply(options).error(R.mipmap.icon_hard).into(imgUser);
        String userName = SPUtils.get(mContext, "userName", "") + "";
        String userPhone = SPUtils.get(mContext, "userPhone", "") + "";
        String jobName = SPUtils.get(mContext, "jobName", "") + "";
        String pwsName = SPUtils.get(mContext, "PwsName", "") + "";
        String cjName = SPUtils.get(mContext, "CjName", "") + "";
        String gqName = SPUtils.get(mContext, "GqName", "") + "";

        tvName.setText("姓名:" + userName + (StringUtils.isEmpty(jobName) ? "" : "   职务:" + jobName) + "\n手机号:" + StringUtils.maskString(userPhone, 3, 7));
        tvJob.setText(pwsName + (StringUtils.isEmpty(cjName) ? "" : " | " + cjName) + (StringUtils.isEmpty(gqName) ? "" : " | " + gqName));
    }

    private void initView() {
//        mTextUserId = findViewById(R.id.tv_user_id);
//        mTextNickname = findViewById(R.id.tv_nickname);
//        mImageAvatar = findViewById(R.id.iv_avatar);

        findViewById(R.id.btn_call).setOnClickListener(v -> {
            Intent intent = new Intent(mContext, CallActivity.class);
            startActivity(intent);
        });

        findViewById(R.id.btn_group_call).setOnClickListener(v -> {
            Intent intent = new Intent(mContext, GroupCallActivity.class);
            startActivity(intent);
        });
        findViewById(R.id.imgToggle).setOnClickListener(v -> {
            if (StringUtils.isFastClick()) {
                return;
            }
            exitDialog();
        });

//        mImageAvatar.setOnClickListener(v -> {
//            showLogoutDialog();
//        });
    }

    private void showLogoutDialog() {
        final Dialog dialog = new Dialog(this, R.style.LogoutDialogStyle);
        dialog.setContentView(R.layout.app_dialog_logout);
        Button btnPositive = (Button) dialog.findViewById(R.id.btn_positive);
        Button btnNegative = (Button) dialog.findViewById(R.id.btn_negative);
        btnPositive.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                logout();
            }
        });
        btnNegative.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                dialog.dismiss();
            }
        });
        dialog.show();
    }

    private void logout() {
        TUILogin.logout(new TUICallback() {
            @Override
            public void onSuccess() {
                LogUtils.e("TAG", "logout success");
                SettingsConfig.userId = "";
                SettingsConfig.userName = "";
                SettingsConfig.userAvatar = "";
                TUILogin.removeLoginListener(mLoginListener);
            }

            @Override
            public void onError(int errorCode, String errorMessage) {
                LogUtils.e("TAG", "logout failed, errorCode: " + errorCode + " , errorMessage: " + errorMessage);
            }
        });
    }

    private final TUILoginListener mLoginListener = new TUILoginListener() {
        @Override
        public void onKickedOffline() {
            super.onKickedOffline();
            LogUtils.e("TAG", "You have been kicked off the line. Please login again!");
            com.tencent.qcloud.tuicore.util.ToastUtil.toastLongMessage(getString(R.string.app_user_kicked_offline));
            logout();
        }

        @Override
        public void onUserSigExpired() {
            super.onUserSigExpired();
            LogUtils.e("TAG", "Your user signature information has expired");
            com.tencent.qcloud.tuicore.util.ToastUtil.toastLongMessage(getString(R.string.app_user_sig_expired));
            logout();
        }
    };

//    @Override
//    protected void onDestroy() {
//        super.onDestroy();
//        TUILogin.removeLoginListener(mLoginListener);
//    }

    @Override
    protected void onStart() {
        super.onStart();
        lca();
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            if (!Settings.canDrawOverlays(mContext)) {
                Intent intent = new Intent(Settings.ACTION_MANAGE_OVERLAY_PERMISSION,
                        Uri.parse("package:" + getPackageName()));
                startActivity(intent);
            }
        }
    }

    @Override
    protected void onRestart() {
        super.onRestart();
        lca();
        initData();
        upVersion();
        String insertTime = SPUtils.get(mContext, "benS", "") + "";
        if (!StringUtils.isEmpty(insertTime)) {
            upLogInfo(insertTime);
        }
    }

    private void lca() {
        if (ContextCompat.checkSelfPermission(mContext, Manifest.permission.ACCESS_FINE_LOCATION) == PackageManager.PERMISSION_GRANTED ||
                ContextCompat.checkSelfPermission(mContext, Manifest.permission.ACCESS_COARSE_LOCATION) == PackageManager.PERMISSION_GRANTED) {
            if (!DavyTx.locationUpdatesActive) {
                DavyTx.locationUpdates();
            }
        } else {
            ActivityCompat.requestPermissions(MainActivity.this, new String[]{Manifest.permission.ACCESS_COARSE_LOCATION, Manifest.permission.ACCESS_FINE_LOCATION}, 1001);
        }
    }

    private void upTrajectory() {
        Map<String, Object> map = new HashMap();
        map.put("time", StringUtils.isEmpty(DavyTx.mLatitude) ? "0" : DavyTx.mLatitude + "");
        map.put("loginfo", StringUtils.isEmpty(DavyTx.mLongitude) ? "0" : DavyTx.mLongitude + "");

        map.put("versions", StringUtils.getVerName(mContext));
        map.put("uname", SPUtils.get(mContext, "userPhone", ""));

        String json = new Gson().toJson(map);
        LogUtils.e("TAG", "json--->" + json);

        HttpClient.getInstance().post(HttpClient.gUrl + CommonHttpConsts.upTrajectory, "upTrajectory")
                .upJson(json)
                .execute(new HttpCallbackData() {

                    @Override
                    public void onSuccess(int code, String msg, String info) {
                        LogUtils.e("TAG", "info:" + info);
                    }
                });
    }

    private void upLogInfo(String insertTime) {
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("time", insertTime);
        jsonObject.put("loginfo", SPUtils.get(mContext, "benE", ""));
        jsonObject.put("versions", StringUtils.getVerName(mContext));
        jsonObject.put("uname", SPUtils.get(mContext, "userPhone", ""));

        LogUtils.e("TAG", "jsonObject--->" + jsonObject.toString());

        HttpClient.getInstance().post(HttpClient.gUrl + CommonHttpConsts.upLogInfo, "upLogInfo")
                .upJson(jsonObject.toString())
                .execute(new HttpCallbackData() {

                    @Override
                    public void onSuccess(int code, String msg, String info) {
                        LogUtils.e("TAG", "info:" + info);
                        if (code == 200) {
                            SPUtils.put(mContext, "benE", "");
                            SPUtils.put(mContext, "benS", "");
                        }
                    }
                });
    }

    public void exitDialog() {
        AlertDialog.Builder builder = new AlertDialog.Builder(mContext, R.style.dialog);
        LayoutInflater inflater = LayoutInflater.from(mContext);
        View v = inflater.inflate(R.layout.dialog_exit, null);
        TextView tvDelete = v.findViewById(R.id.tvDelete);
        TextView tvSave = v.findViewById(R.id.tvSave);
        AlertDialog dialog = builder.create();
        dialog.setCanceledOnTouchOutside(false);//点击屏幕不消失

        if (!dialog.isShowing()) {//此时提示框未显示
            dialog.show();
        }
        dialog.getWindow().clearFlags(WindowManager.LayoutParams.FLAG_ALT_FOCUSABLE_IM);
        dialog.getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_ADJUST_NOTHING);

        //自定义的东西
        dialog.getWindow().setContentView(v);
        tvDelete.setOnClickListener(v1 -> dialog.dismiss());

        tvSave.setOnClickListener(view -> {
            if (StringUtils.isFastClick()) {
                return;
            }
            SPUtils.put(mContext, "userType", false);//登录状态
            startActivity(new Intent(mContext, LoginActivity.class));
            dialog.dismiss();
            finish();
        });
    }


    //系统升级
    private IndicatorProgressBar mProgress;
    private RelativeLayout rl_softu;
    private LinearLayout lyDialog;
    private TextView tvContext;
    private String destfiledir;
    private String downloadurl;
    private String app_name = "";
    private TextView tvDialogCancel, tvDialogConfirm;
    private int isforcedupdate = 0;

    private void upVersion() {
        HttpClient.getInstance().get(HttpClient.gUrl + CommonHttpConsts.upVersion, "upVersion")
                .params("version", StringUtils.getVerName(mContext))
                .params("railway", DavyTx.railway)
                .execute(new HttpCallbackData() {

                    @RequiresApi(api = Build.VERSION_CODES.O)
                    @Override
                    public void onSuccess(int code, String msg, String info) {
                        LogUtils.e("TAG", "info:" + info);
                        if (code == 200 && !StringUtils.isEmpty(info)) {
                            String string = StringUtils.decompressForGzip(info);

                            Map dataMap = JSON.parseObject(string, Map.class);
                            if (dataMap.size() > 0) {
                                downloadurl = dataMap.get("url") + "";
                                app_name = dataMap.get("name") + "";
                                tvContext.setText(dataMap.get("content") + "");
                                String isfo = dataMap.get("force") + "";
                                if (!StringUtils.isEmpty(isfo)) {
                                    isforcedupdate = Integer.valueOf(isfo);
                                }
                                lyDialog.setVisibility(View.VISIBLE);
                                if (isforcedupdate == 1) {
                                    tvDialogCancel.setVisibility(View.GONE);
                                } else {
                                    tvDialogCancel.setVisibility(View.VISIBLE);
                                }
                            }
                        }
                    }
                });
    }


    private void downloadNewFile() {
        OkGo.<File>get(downloadurl).tag(mContext).execute(new FileCallback(destfiledir, app_name) {
            @Override
            public void onSuccess(Response<File> response) {
                String s = destfiledir + "/" + app_name;
                rl_softu.setVisibility(View.GONE);
                installApk(s);
            }


            @Override
            public void downloadProgress(Progress progress) {
                super.downloadProgress(progress);
                LogUtils.e("TAG", "下载进度：" + (int) (progress.fraction * 100));
                mProgress.setProgress((int) (progress.fraction * 100));
            }

            @Override
            public void onError(Response<File> response) {
                super.onError(response);
                runOnUiThread(() -> {
                    rl_softu.setVisibility(View.GONE);
                    ToastUtil.show("网络中断，请稍后再试！");
                });
            }
        });
    }

    /**
     * 安装apk
     */
    public void installApk(String apkPath) {
        if (TextUtils.isEmpty(apkPath)) {
            ToastUtil.show("更新失败！未找到安装包");
            return;
        }

        LogUtils.e("TAG", "开始执行安装: " + apkPath);
        File apkFile = new File(apkPath);
        Intent intent = new Intent(Intent.ACTION_VIEW);
        intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
            LogUtils.e("TAG", "版本大于 N ，开始使用 fileProvider 进行安装");
            intent.setFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
            Uri contentUri = FileProvider.getUriForFile(mContext, "com.davy.dawei.fileprovider", apkFile);
            intent.setDataAndType(contentUri, "application/vnd.android.package-archive");
            mContext.startActivity(intent);
        } else {
            LogUtils.e("TAG", "正常进行安装");
            intent.setDataAndType(Uri.fromFile(apkFile), "application/vnd.android.package-archive");
            mContext.startActivity(intent);
        }
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK && event.getAction() == KeyEvent.ACTION_DOWN) {
            if ((System.currentTimeMillis() - mExitTime) > 2000) {
                ToastUtil.show("再按一次退出程序");
                mExitTime = System.currentTimeMillis();
            } else {
                ScreenManager.getScreenManager().exit();
            }
            return true;
        }
        return super.onKeyDown(keyCode, event);
    }

}